package com.yb.xczx.cloud.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.yb.core.model.message.XczxRabbitMQMessage;
import com.yb.core.model.XczxResult;
import com.yb.xczx.cloud.system.constant.RabbitConstant;
import com.yb.xczx.cloud.system.service.IRabbitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/9/16 12:36
 * FileName: RabbitServiceImpl
 * Description: rabbit
 */
@Service
@Slf4j
public class RabbitServiceImpl implements IRabbitService {

    @Autowired
    RabbitTemplate rabbitTemplate;


    private ConcurrentHashMap map = new ConcurrentHashMap();

    @Override
    public XczxResult send(String msg) {

        log.info("send msg={}", msg);

        String msgId = UUID.randomUUID().toString();
        XczxRabbitMQMessage rabbitVo = XczxRabbitMQMessage.builder()
                .rabbitId(msgId)
                .exchange(RabbitConstant.DemoQueue.DEMO_EXCHANGE)
                .routingKey(RabbitConstant.DemoQueue.DEMO_ROUTING_KEY)
                        .build();
        rabbitVo.setContent(msg);
        CorrelationData correlationData = new CorrelationData(msgId);
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setMessageId(msgId);
        messageProperties.setCorrelationId(msgId);
        Message message = new Message(JSONObject.toJSONBytes(rabbitVo), messageProperties);
        ReturnedMessage returnedMessage = new ReturnedMessage(message, 0, "123", rabbitVo.getExchange(),rabbitVo.getRoutingKey());
        correlationData.setReturned(returnedMessage);
//        rabbitTemplate.convertAndSend(RabbitConstant.DemoQueue.DEMO_EXCHANGE,
//                RabbitConstant.DemoQueue.DEMO_ROUTING_KEY,rabbitVo,correlationData);
        rabbitTemplate.convertAndSend(rabbitVo.getExchange(),
                rabbitVo.getRoutingKey(), rabbitVo.getContent(), correlationData);
        log.info("send success msg={}", msg);
        return XczxResult.success();
    }
}

